<template>
  <div class="container">
    <el-dialog
      title="添加加工商品"
      :visible.sync="dialog.centerDialogVisible"
      @open="openData"
      @close="cancel"
      center
      width="1500px"
    >
      <el-select
        v-model="is_avg"
        style="margin-bottom: 5px"
        placeholder="请选择入库方式"
      >
        <el-option
          v-for="item in is_avgList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <div class="top">
        <el-select
          v-model="procurement.value"
          :multiple="false"
          filterable
          remote
          reserve-keyword
          placeholder="请选择调入采购员"
          :remote-method="insideProcurement"
          :loading="procurement.loading"
          @change="insidebuyer(procurement.value)"
        >
          <el-option
            v-for="item in procurement.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="commodity"
          placeholder="请搜索加工商品"
          :remote-method="insideRemoteMethod"
          :loading="inside.loading"
        >
          <el-option
            v-for="item in inside.option"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-search"
          @click="addGoods()"
          >添加</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        max-height="500"
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="Name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="Code"
          label="商品编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="ClassName"
          label="品类名称"
          align="center"
        ></el-table-column>
        <el-table-column width="1200px" label="原料">
          <template slot-scope="scope">
            <div class="top">
              <el-select
                :multiple="false"
                filterable
                remote
                center
                reserve-keyword
                v-model="scope.row.commodity"
                @change="onCommodity(scope)"
                placeholder="请搜索原料"
                :remote-method="
                  q => {
                    insideRemoteMethods(q, scope);
                  }
                "
                :loading="scope.row.inside.loading"
              >
                <el-option
                  v-for="item in scope.row.inside.option"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-button
                size="medium"
                type="primary"
                class="handleSearch"
                icon="el-icon-search"
                @click="addScopeGoods(scope)"
                >添加</el-button
              >
            </div>
            <el-table
              :data="scope.row.tableData"
              border
              style="width: 100%"
            >
              <el-table-column
                prop="commodityName"
                align="center"
                label="原料名称"
                width="180"
              >
              </el-table-column>
              <el-table-column prop="name" label="批次">
                <template slot-scope="scopes">
                  <div class="top">
                    <el-select
                      v-model="scopes.row.batch"
                      style="margin-bottom: 5px"
                      placeholder="请选择批次"
                    >
                      <el-option
                        v-for="item in scopes.row.inside.option"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                    <el-button
                      size="medium"
                      type="primary"
                      class="handleSearch"
                      icon="el-icon-search"
                      @click="onBatch(scopes)"
                      >添加</el-button
                    >
                  </div>
                  <el-table
                    :data="scopes.row.tableData"
                    border
                    style="width: 100%"
                  >
                    <el-table-column
                      prop="code"
                      align="center"
                      label="批次编码"
                    >
                    </el-table-column>
                    <el-table-column prop="price" align="center" label="价格">
                    </el-table-column>
                    <el-table-column
                      prop="stock_num"
                      align="center"
                      label="批次库存"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="rk_spec"
                      align="center"
                      label="入库箱规"
                    >
                    </el-table-column>
                    <el-table-column width="160px" label="数量" align="center">
                      <template slot-scope="scopess">
                        <el-input-number
                          :controls="false"
                          @change="total(scope, scopes, scopess)"
                          v-model="scopess.row.num"
                          :min="0"
                          controls-position="right"
                          :precision="2"
                          :step="1"
                          size="mini"
                        ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column prop="total" align="center" label="总价">
                    </el-table-column>
                    <el-table-column label="操作" width="100px" align="center">
                      <template slot-scope="scopess">
                        <el-button
                          size="small"
                          type="danger"
                          @click="removess(scope, scopes, scopess)"
                          icon="el-icon-delete"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column
                prop="total"
                align="center"
                label="总价"
                width="100"
              >
              </el-table-column>
              <el-table-column label="操作" width="100px" align="center">
                <template slot-scope="scopes">
                  <el-button
                    size="small"
                    type="danger"
                    @click="removes(scope, scopes)"
                    icon="el-icon-delete"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="total" align="center" label="总价" width="100">
        </el-table-column>
        <el-table-column width="180px" label="加工数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              :controls="false"
              v-model="scope.row.num"
              :min="0"
              controls-position="right"
              :precision="2"
              :step="1"
              size="mini"
              @change="taxrate(scope)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="systemNum"
          label="系统计算单价"
          align="center"
        ></el-table-column>
        <el-table-column width="180px" label="入库单价" align="center">
          <template slot-scope="scope">
            <el-input-number
              :controls="false"
              v-model="scope.row.price"
              :min="0"
              controls-position="right"
              :precision="4"
              :step="1"
              size="mini"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="qty" label="箱数" align="center">
        </el-table-column>
        <el-table-column width="150px" label="入库规格" align="center">
          <template slot-scope="scope">
            <el-select
              @change="sonCount(scope)"
              v-model="scope.row.rkSpec"
              placeholder="请选择规格"
            >
              <el-option
                v-for="item in scope.row.rkSpecList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="生产日期" align="center" width="250px">
          <template slot-scope="scope">
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="scope.row.produce_date"
              @change="timeCenter(scope)"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="保质期（天）" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              @change="timeCenter(scope)"
              v-model="scope.row.shelf_life"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="到期日" align="center" width="250px">
          <template slot-scope="scope">
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="timeCenter(scope)"
              v-model="scope.row.due_date"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="180px">
          <template slot-scope="scope">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="scope.row.remark"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="350px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="addSpec(scope)"
              icon="el-icon-circle-plus-outline"
              >添加规格</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="remove(scope)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        width="400px"
        title="添加规格"
        :visible.sync="specDialog.centerDialogVisible"
        append-to-body
        center
        @close="cancelSpec"
      >
        <el-form label-width="100px" label-position="center">
          <el-form-item label="规格：">
            <el-input-number
              size="small"
              :controls="false"
              v-model="spec"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelSpec">取 消</el-button>
          <el-button type="primary" @click="specNum()">确 定</el-button>
        </span>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirms">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCanProductList,
  selectErpGoodsData,
  getProductInfo,
  materialBatch,
  productnew
} from "@/api/process/processList";
import { getList } from "@/api/putStorage/putStotageList";
export default {
  props: {
    dialog: Object
  },
  data() {
    return {
      mainData: [],
      tableData: [],
      procurement: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: ""
      },
      buyer: {
        name: "",
        code: "",
        id: ""
      },
      procurementList: [],
      inside: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      batch: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      commodity: "",
      is_avg: "",

      specDialog: {
        centerDialogVisible: false,
        specId: ""
      },
      is_avgList: [
        {
          value: "0",
          label: "成本价入库"
        },
        {
          value: "1",
          label: "平均价入库"
        }
      ],
      spec: 0
    };
  },
  methods: {
    //取消
    cancel() {
      this.dialog.centerDialogVisible = false;
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.procurement = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: ""
      };
      this.is_avg = "";
      this.commodity = "";

      this.mainData = [];
      this.tableData = [];
    },
    getCatch() {
      let data = {
        page: 1,
        limit: 500,
        keyword: "",
        is_avg: this.is_avg,
        dccode: this.dialog.dccode
      };
      //获取商品
      materialBatch(data).then(res => {
        this.batch.list = res.data.paginate.data;
        this.batch.option = res.data.paginate.data.map(item => {
          return { value: `${item.Code}`, label: `${item.Name}` };
        });
      });
    },
    getData(prop = "") {
      let data = {
        page: 1,
        limit: 50,
        goods_code: prop
      };
      //获取商品
      selectErpGoodsData(data).then(res => {
        this.mainData = res.data.paginate.data;
        this.inside.option = res.data.paginate.data.map(item => {
          return { value: `${item.Code}`, label: `${item.Name}` };
        });
      });
    },
    getScopeData(prop = "", index) {
      let data = {
        page: 1,
        limit: 50,
        goods_code: prop
      };
      //获取商品
      selectErpGoodsData(data).then(res => {
        this.tableData[index].inside.list = res.data.paginate.data;
        this.tableData[index].inside.option = res.data.paginate.data.map(
          item => {
            return { value: `${item.Code}`, label: `${item.Name}` };
          }
        );
        this.$set(this.tableData, index, this.tableData[index]);
      });
    },
    getBatchData(prop = "", index) {
      let data = {
        page: 1,
        limit: 50,
        goods_code: prop
      };
      //获取商品
      selectErpGoodsData(data).then(res => {
        this.tableData[index].inside.list = res.data.paginate.data;
        this.tableData[index].inside.option = res.data.paginate.data.map(
          item => {
            return { value: `${item.Code}`, label: `${item.Name}` };
          }
        );
        this.$set(this.tableData, index, this.tableData[index]);
      });
    },
    //时间计算
    timeCenter(scope, num) {
      if (scope.row.produce_date && scope.row.shelf_life) {
        var produce_date_stamp = new Date(scope.row.produce_date).getTime();
        var shelf_life_stamp = 86400000 * scope.row.shelf_life;
        var due_date_stamp = this.timestampToDatetime(
          produce_date_stamp + shelf_life_stamp
        );
        scope.row.due_date = due_date_stamp;
      } else if (
        scope.row.produce_date &&
        !scope.row.shelf_life &&
        scope.row.due_date
      ) {
        var produce_date_stamp = new Date(scope.row.produce_date).getTime();
        var due_date_stamp = new Date(scope.row.due_date).getTime();
        var shelf_life_stamp = Math.round(
          (due_date_stamp - produce_date_stamp) / 86400000
        );
        scope.row.shelf_life = shelf_life_stamp;
      } else if (
        !scope.row.produce_date &&
        scope.row.shelf_life &&
        scope.row.due_date
      ) {
        var shelf_life_stamp = 86400000 * scope.row.shelf_life;
        var due_date_stamp = new Date(scope.row.due_date).getTime();
        var produce_date_stamp = this.timestampToDatetime(
          due_date_stamp - shelf_life_stamp
        );
        scope.row.produce_date = produce_date_stamp;
      }
    },
    timestampToDatetime(timestamp) {
      let date = new Date(timestamp);
      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2);
      let day = ("0" + date.getDate()).slice(-2);
      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    purchase() {
      let datas = {
        key: ""
      };
      //获取采购员
      getList(datas).then(res => {
        this.procurement.options = res.data.map(item => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            id: `${item.id}`
          };
        });
        this.procurementList = res.data;
      });
    },
    //获取采购员name,code,id
    insidebuyer(e) {
      let center = this.procurementList.filter(res => {
        return res.code == e;
      });
      this.buyer = {
        name: center[0].name,
        code: center[0].code,
        id: center[0].id
      };
    },
    //搜索采购员
    insideProcurement(query) {
      if (query !== "") {
        this.getProcurement(query);
      } else {
        this.procurement.options = [];
      }
    },
    //获取采购员列表
    getProcurement(query) {
      let data = {
        key: query
      };
      this.procurement.loading = true;
      getList(data).then(res => {
        this.procurement.list = res.data.map(item => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            id: `${item.id}`
          };
        });
        this.procurement.loading = false;
        this.procurement.options = this.procurement.list.filter(item => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.procurementList = res.data;
      });
    },
    openData() {
      this.getData();
      this.purchase();
    },
    addSpec(scope) {
      this.specDialog.centerDialogVisible = true;
      this.specDialog.specId = scope.row.goods_bar_code;
    },
    cancelSpec() {
      this.specDialog.centerDialogVisible = false;
      this.specDialog.specId = "";
      this.spec = 0;
    },
    //规格确定
    specNum() {
      if (this.spec) {
        this.tableData.forEach((res, index) => {
          if (res.goods_bar_code == this.specDialog.specId) {
            res.rkSpecList.push({
              value: this.spec,
              label: this.spec
            });
            this.$set(this.tableData, index, res);
            this.cancelSpec();
          }
        });
      } else {
        this.$message({
          type: "info",
          message: "请输入规格"
        });
      }
    },
    sonCount(scope) {
      if (scope.row.num) {
        scope.row.qty = (
          parseFloat(scope.row.num) / parseFloat(scope.row.rkSpec)
        ).toFixed(4);
        this.$set(this.tableData, scope.$index, scope.row);
      } else {
        scope.row.qty = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    //删除
    remove(scope) {
      let code = scope.row.BarCode;
      this.tableData.forEach((res, index) => {
        if (res.BarCode == code) {
          this.tableData.splice(index, 1);
        }
      });
    },
    removes(scope, scopes) {
      let code = scopes.row.BarCode;
      scope.row.tableData.forEach((res, index) => {
        if (res.BarCode == code) {
          scope.row.tableData.splice(index, 1);
          scope.row.total = 0;
          scope.row.tableData.forEach(res => {
            scope.row.total = (
              parseFloat(res.total) + parseFloat(scope.row.total)
            ).toFixed(4);
          });
          if (scope.row.num) {
            scope.row.systemNum = parseFloat(
              scope.row.total / scope.row.num
            ).toFixed(4);
          }

          this.$set(this.tableData, scope.$index, scope.row);
        }
      });
    },
    removess(scope, scopes, scopess) {
      let code = scopess.row.code;
      scopes.row.tableData.forEach((res, index) => {
        if (res.code == code) {
          scopes.row.tableData.splice(index, 1);
          scopes.row.total = 0;
          scopes.row.tableData.forEach(res => {
            scopes.row.total = (
              parseFloat(res.total) + parseFloat(scopes.row.total)
            ).toFixed(4);
          });
          this.$set(scope.row.tableData, scopes.$index, scopes.row);
          scope.row.total = 0;
          scope.row.tableData.forEach(res => {
            scope.row.total = (
              parseFloat(res.total) + parseFloat(scope.row.total)
            ).toFixed(4);
          });
          if (scope.row.num) {
            scope.row.systemNum = parseFloat(
              scope.row.total / scope.row.num
            ).toFixed(4);
          }

          this.$set(this.tableData, scope.$index, scope.row);
        }
      });
    },
    onCommodity(scope) {
      this.$set(this.tableData, scope.$index, scope.row);
    },
    // 添加商品
    addGoods() {
      if (this.commodity) {
        if (this.tableData.length > 0) {
          let bool = this.tableData.some(res => {
            return res.Code == this.commodity;
          });
          if (bool) {
            this.$message({
              type: "info",
              message: "该商品已添加"
            });
          } else {
            let every = this.mainData.filter(res => {
              return this.commodity == res.Code;
            });

            every[0].inside = {
              innerVisible: false,
              option: [],
              value: "",
              list: [],
              loading: false
            };
            every[0].systemNum = 0;
            every[0].total = 0;
            every[0].commodity = "";
            every[0].commodityName = "";
            every[0].tableData = [];
            every[0].num = 0;
            every[0].price = 0;
            every[0].rkSpecList = [];
            every[0].rkSpec = parseFloat(every[0].rk_spec);
            every[0].rkSpecList.push({
              label: parseFloat(every[0].rk_spec),
              value: parseFloat(every[0].rk_spec)
            });
            every[0].qty = every[0].num / every[0].rkSpec;
            this.tableData.push(every[0]);
            this.getScopeData("", this.tableData.length - 1);
          }
        } else {
          let every = this.mainData.filter(res => {
            return this.commodity == res.Code;
          });
          every[0].inside = {
            innerVisible: false,
            option: [],
            value: "",
            list: [],
            loading: false
          };
          every[0].total = 0;
          every[0].commodity = "";
          every[0].commodityName = "";
          every[0].tableData = [];
          every[0].num = 0;
          every[0].price = 0;
          every[0].rkSpecList = [];
          every[0].rkSpec = parseFloat(every[0].rk_spec);
          every[0].rkSpecList.push({
            label: parseFloat(every[0].rk_spec),
            value: parseFloat(every[0].rk_spec)
          });
          every[0].qty = every[0].num / every[0].rkSpec;
          this.tableData.push(every[0]);
          this.getScopeData("", this.tableData.length - 1);
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择加工商品"
        });
      }
    },

    // 添加原料
    addScopeGoods(scope) {
      if (scope.row.tableData.length > 0) {
        let bool = scope.row.tableData.some(res => {
          return res.Code == scope.row.commodity;
        });
        if (bool) {
          this.$message({
            type: "info",
            message: "该商品已添加"
          });
        } else {
          let every = scope.row.inside.list.filter(res => {
            return scope.row.commodity == res.Code;
          });
          every[0].inside = {
            innerVisible: false,
            option: [],
            value: "",
            list: [],
            loading: false
          };
          every[0].total = 0;
          every[0].batch = "";
          every[0].tableData = [];
          every[0].commodityName = every[0].Name;
          scope.row.tableData.push(every[0]);
          this.getCatch(
            scope.row.commodity,
            scope.row.tableData[scope.row.tableData.length - 1]
          );
        }
      } else {
        let every = scope.row.inside.list.filter(res => {
          return scope.row.commodity == res.Code;
        });
        every[0].inside = {
          innerVisible: false,
          option: [],
          value: "",
          list: [],
          loading: false
        };
        every[0].total = 0;
        every[0].batch = "";
        every[0].tableData = [];
        every[0].commodityName = every[0].Name;
        scope.row.tableData.push(every[0]);
        this.getCatch(
          scope.row.commodity,
          scope.row.tableData[scope.row.tableData.length - 1]
        );
      }
    },
    getCatch(commodity, scope) {
      let data = {
        page: 1,
        limit: 500,
        keyword: commodity,
        is_avg: this.is_avg,
        dccode: this.dialog.dccode
      };
      //获取商品
      materialBatch(data).then(res => {
        scope.inside.list = res.data.batchlist;
        scope.inside.option = res.data.batchlist.map(item => {
          return {
            value: `${item.code}`,
            label: `${item.code}(价格：${item.price}){箱规${item.rk_spec}}`
          };
        });
      });
    },
    //添加批次
    onBatch(scope) {
      if (scope.row.tableData.length > 0) {
        let bool = scope.row.tableData.some(res => {
          return res.code == scope.row.batch;
        });
        if (bool) {
          this.$message({
            type: "info",
            message: "该批次已添加"
          });
        } else {
          let every = scope.row.inside.list.filter(res => {
            return scope.row.batch == res.code;
          });

          every[0].num = 0;
          every[0].total = 0;
          scope.row.tableData.push(every[0]);
        }
      } else {
        let every = scope.row.inside.list.filter(res => {
          return scope.row.batch == res.code;
        });
        every[0].num = 0;
        every[0].total = 0;
        scope.row.tableData.push(every[0]);
      }
    },
    // 总价
    total(scope, scopes, scopess) {
      scopess.row.total = parseFloat(
        scopess.row.num * scopess.row.price
      ).toFixed(4);
      this.$set(scopes.row.tableData, scopess.$index, scopess.row);
      scopes.row.total = 0;
      scopes.row.tableData.forEach(res => {
        scopes.row.total = (
          parseFloat(res.total) + parseFloat(scopes.row.total)
        ).toFixed(4);
      });
      this.$set(scope.row.tableData, scopes.$index, scopes.row);
      scope.row.total = 0;
      scope.row.tableData.forEach(res => {
        scope.row.total = (
          parseFloat(res.total) + parseFloat(scope.row.total)
        ).toFixed(4);
      });
      if (scope.row.num) {
        scope.row.systemNum = parseFloat(
          scope.row.total / scope.row.num
        ).toFixed(4);
      }

      this.$set(this.tableData, scope.$index, scope.row);
    },
    // 获取商品方法
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getData(query);
      } else {
        this.inside.options = [];
      }
    },
    insideRemoteMethods(query, scope) {
      if (query !== "") {
        this.getScopeData(query, scope.$index);
      } else {
        scope.row.inside.options = [];
      }
    },
    //修改数量和规格
    taxrate(scope) {
      scope.row.qty = parseFloat(scope.row.num) / parseFloat(scope.row.rkSpec);
      if (scope.row.total && scope.row.num) {
        scope.row.systemNum = parseFloat(
          scope.row.total / scope.row.num
        ).toFixed(4);
      } else {
        scope.row.systemNum = 0;
      }
      this.$set(this.tableData, scope.$index, scope.row);
    },
    //确定
    confirms() {
      this.$confirm("加工是否提交", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true
      }).then(() => {
        if (!this.is_avg) {
          this.$message({
            type: "info",
            message: "请选择入库方式"
          });
          return false;
        }
        if (this.tableData.length == 0) {
          this.$message({
            type: "info",
            message: "请添加加工商品"
          });
          return false;
        }

        let batchArr = [];
        this.tableData.forEach(res => {
          if (res.tableData.length > 0) {
            res.tableData.forEach(item => {
              if (item.tableData.length > 0) {
                item.tableData.forEach(prop => {
                  if (!prop.num) {
                    batchArr.push(
                      `商品：${res.Name}(${res.Code}) - 原料：${
                        item.commodityName
                      } - 批次：${prop.code}`
                    );
                  }
                });
              }
            });
          }
        });
        if (batchArr.length > 0) {
          const h = this.$createElement;
          let batchStr = [];
          batchArr.forEach(res => {
            batchStr.push(h("div", null, res));
          });
          this.$confirm(h("p", null, [batchStr]), "以下批次没有添加数量", {
            customClass: "tests",
            center: true,
            showCancelButton: false,
            confirmButtonText: "确定",
            type: "warning"
          })
            .then(() => {
              console.log(99999999);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        } else {
          let priceboolArr = [];
          this.tableData.forEach(res => {
            if ((res.num * res.price).toFixed(4) !== res.total) {
              priceboolArr.push(res.Name + "(" + res.Code + ")");
            }
          });

          if (priceboolArr.length > 0) {
            const h = this.$createElement;
            let priceboolStr = [];
            priceboolArr.forEach(res => {
              priceboolStr.push(h("div", null, res));
            });
            if (priceboolStr.length > 0) {
            } else {
            }
            this.$confirm(
              h("p", null, [priceboolStr]),
              "以下商品入库总价与原料总价不一致是否继续提交?",
              {
                customClass: "test",
                center: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            )
              .then(() => {
                let dataArr = [];
                this.tableData.forEach((res, index) => {
                  dataArr.push({
                    goods_name: res.Name,
                    erp_goods_code: res.Code,
                    num: res.num,
                    price: res.price,
                    unit: res.Unit,
                    qty: res.qty,
                    spec: res.Spec,
                    remark: res.remark,
                    category_code: res.ClassCode,
                    category_name: res.ClassName,
                    rk_spec: res.rkSpec,
                    goods_bar_code: res.BarCode,
                    produce_date: res.produce_date || "",
                    shelf_life: res.shelf_life || "",
                    due_date: res.due_date || "",
                    material: []
                  });
                  if (res.tableData.length > 0) {
                    res.tableData.forEach((item, indexs) => {
                      dataArr[index].material.push({
                        erp_goods_code: item.Code,
                        goods_bar_code: item.BarCode,
                        goods_name: item.Name,
                        num: 0,
                        unit: item.Unit,
                        spec: item.Spec,
                        material_batch: []
                      });
                      if (item.tableData.length > 0) {
                        item.tableData.forEach(prop => {
                          dataArr[index].material[indexs].material_batch.push({
                            batch_id: prop.id,
                            num: prop.num
                          });
                        });
                      }
                    });
                  }
                });
                let data = {
                  is_avg: this.is_avg,
                  dccode: this.dialog.dccode,
                  buyer_id: this.buyer.id,
                  buyer_code: this.buyer.code,
                  buyer_name: this.buyer.name,
                  product_data: JSON.stringify(dataArr)
                };
                productnew(data).then(res => {
                  if (res.code == 0) {
                    this.$message({
                      type: "success",
                      message: res.msg || res.message
                    });
                    this.$emit("upData");
                    this.cancel();
                  }
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消"
                });
              });
          } else {
            let dataArr = [];
            this.tableData.forEach((res, index) => {
              dataArr.push({
                goods_name: res.Name,
                erp_goods_code: res.Code,
                num: res.num,
                price: res.price,
                unit: res.Unit,
                qty: res.qty,
                spec: res.Spec,
                remark: res.remark,
                category_code: res.ClassCode,
                category_name: res.ClassName,
                rk_spec: res.rkSpec,
                goods_bar_code: res.BarCode,
                produce_date: res.produce_date || "",
                shelf_life: res.shelf_life || "",
                due_date: res.due_date || "",
                material: []
              });
              if (res.tableData.length > 0) {
                res.tableData.forEach((item, indexs) => {
                  dataArr[index].material.push({
                    erp_goods_code: item.Code,
                    goods_bar_code: item.BarCode,
                    goods_name: item.Name,
                    num: 0,
                    unit: item.Unit,
                    spec: item.Spec,
                    material_batch: []
                  });
                  if (item.tableData.length > 0) {
                    item.tableData.forEach(prop => {
                      dataArr[index].material[indexs].material_batch.push({
                        batch_id: prop.id,
                        num: prop.num
                      });
                    });
                  }
                });
              }
            });
            let data = {
              is_avg: this.is_avg,
              dccode: this.dialog.dccode,
              buyer_id: this.buyer.id,
              buyer_code: this.buyer.code,
              buyer_name: this.buyer.name,
              product_data: JSON.stringify(dataArr)
            };
            productnew(data).then(res => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: res.msg || res.message
                });
                this.$emit("upData");
                this.cancel();
              }
            });
          }
        }
      });
    }
  }
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}

.top {
  margin-bottom: 5px;
}
</style>
